<template>
  <div class="app-page">
    <el-table-form ref="form" :model="query">
      <el-form-item :table-form-merge="2" class="merge-item">
        <el-select v-model="dateType" style="width: 170px; margin-right: 2px;">
          <el-option label="录入时间" value="createTime" />
          <el-option label="操作时间" value="modifyTime" />
        </el-select>
        <el-date-picker
          v-model="date"
          type="datetimerange"
          range-separator="至"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          unlink-panels
          :clearable="false"
        />
      </el-form-item>
      <el-form-item prop="orgSNNo" class="merge-item">
        <el-select v-model="orgType" style="width: 170px; margin-right: 2px;">
          <el-option label="发生机构" value="happenOrgSNNo" />
          <el-option label="归属机构" value="orgSNNo" />
        </el-select>
        <el-tree-select
          v-model="orgSNNo"
          clearable
          class="tree-select"
          :popover-width="360"
          :select-params="{
            clearable: true,
            placeholder: '请选择',
            loading: $loadingPlugin.getTreeData
          }"
          :tree-params=" {
            'expand-on-click-node': false,
            'highlight-current': true,
            'filterable': true,
            props:{
              value:'orgSNNo',
              label: 'orgName',
              disabled: 'disabled',
            },
            data: treeData
          }"
          @node-click="selectTreeChange"
          @select-clear="clearSelectTree"
        />
      </el-form-item>
      <el-form-item class="merge-item">
        <el-select v-model="personnelType" style="width: 180px; margin-right: 2px;">
          <el-option label="关联配送员" value="lastOwnerId" />
          <el-option label="归属配送员" value="ownerId" />
        </el-select>
        <el-select v-model="distributor" placeholder="请选择" filterable clearable>
          <el-option
            v-for="item in distributorList"
            :key="item.value"
            :label="item.userName"
            :value="item.userId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="气瓶编号:">
        <el-input v-model.trim="query.bottleCode" placeholder="请输入气瓶编号" clearable />
      </el-form-item>
      <el-form-item label="操作环节:" prop="operateType">
        <el-select v-model="query.operateType" clearable filterable style="width: 100%;" placeholder="请选择">
          <el-option
            v-for="item in operateTypeMap"
            :key="item.value"
            :label="item.desc"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <template v-slot:btns>
        <el-button v-permission="1" type="primary" icon="el-icon-search" @click="search">查询</el-button>
      </template>
    </el-table-form>
    <div style="margin-bottom: 10px;" class="btn-group">
      <div>
        <el-button v-permission="2" type="primary" icon="el-icon-plus" @click="add">新增自有瓶</el-button>
        <el-button v-permission="3" type="primary" icon="el-icon-folder-add" :loading="$loadingPlugin.exportData" @click="exportData">导出</el-button>
      </div>
    </div>
    <lb-table
      ref="lbTable"
      v-el-height-adaptive-table="{bottomOffset:10}"
      border
      highlight-current-row
      element-loading-text="加载中"
      :column="column"
      :data="tableData.data"
      pagination
      :total="tableData.total"
      custom-column
      @fetch="fetchData"
    />
    <add ref="add" :tree-data="treeData" />
  </div>
</template>

<script>
  import {
    queryMap,
    queryOwnersList,
    selfBottleDel,
    selfBottleExport,
    selfBottleList
  } from '@/api'
  import { formatColumnMap, parseTime } from '@/utils'
  import getTreeData from '@/utils/jsonTree'
  import { mapGetters } from 'vuex'
  import moment from 'dayjs'
  import add from './components/add'
  import { mergeAsyncFunc } from '@/utils/mergeAsyncFunc'

  export default {
    name: 'privateBottle',
    components: {
      add
    },
    data() {
      return {
        actionColWidth: 80,
        treeData: [],
        dateType: 'createTime',
        date: [moment(new Date()).format('YYYY-MM-DD') + ' 00:00:00', moment(new Date()).format('YYYY-MM-DD') + ' 23:59:59'],
        orgType: 'happenOrgSNNo',
        orgSNNo: '',
        personnelType: 'lastOwnerId',
        distributor: '',
        distributorList: [],
        query: {
          bottleCode: '',
          operateType: ''
        },
        operateTypeMap: [],
        roleTypeList: [],
        tableData: {
          total: 0,
          data: []
        },
        searchParams: {}
      }
    },
    computed: {
      ...mapGetters([
        'orgList', 'exportDomain'
      ]),
      column: function() {
        return [
          {
            type: 'index'
          },
          {
            prop: 'bottleCode',
            width: 110,
            label: '气瓶号'
          },
          {
            prop: 'owner',
            width: 110,
            label: '归属配送员'
          },
          {
            prop: 'orgName',
            width: 150,
            label: '归属机构'
          },
          {
            prop: 'createTime',
            label: '录入时间',
            width: 160,
            render: (h, { row }) => <span>{ row.createTime && parseTime(row.createTime, '{y}-{m}-{d} {h}:{i}') }</span>
          },
          {
            prop: 'operateType',
            label: '当前状态',
            width: 110,
            render: (h, { row }) => <span>{ row.operateType && formatColumnMap(this.operateTypeMap, 'value', row.operateType, 'desc') }</span>
          },
          {
            prop: 'modifyTime',
            label: '最后操作时间',
            width: 160,
            render: (h, { row }) => <span>{ row.modifyTime && parseTime(row.modifyTime, '{y}-{m}-{d} {h}:{i}') }</span>
          },
          {
            prop: 'happenOrgName',
            width: 150,
            label: '发生机构'
          },
          {
            prop: 'lastOwner',
            width: 110,
            label: '最后关联配送员'
          },
          {
            prop: 'createUser',
            width: 110,
            label: '录入操作人'
          },
          {
            label: '操作',
            align: 'center',
            fixed: 'right',
            className: 'action-col',
            width: this.actionColWidth,
            render: (h, { row, $index }) => {
              return (
                <div>
                  {<el-link v-permission='4' underline={false} size='mini' type='danger' onClick={() => this.del(row, $index)}>
                    删除
                  </el-link>}
                </div>
              )
            }
          }
        ]
      }
    },
    async created() {
      await Promise.all([this.getTreeData()])
      this.queryOptionsMap()
    },
    methods: {
      // 查询枚举
      async queryOptionsMap() {
        const [res8] = await Promise.all([
          mergeAsyncFunc(queryMap, { enumName: 'InvenChipOperateSelectType' })
        ])
        this.operateTypeMap = res8.data // 订单来源
      },
      // 获取所属机构数据
      async getTreeData() {
        const data = this.orgList.map(item => ({
          label: item.name,
          ...item
        }))
        this.treeData = getTreeData(data)
      },
      _getQuery(obj) {
        const query = {}
        for (const key in obj) {
          if (obj.hasOwnProperty(key)) {
            if (obj[key] !== '') {
              query[key] = obj[key]
            }
          }
        }
        return query
      },
      // 查询处理人列表
      async getOwnersList(org) {
        const res = await queryOwnersList({
          orgId: org || ''
        })
        this.distributorList = res.data
      },
      clearSelectTree() {
        this.distributor = ''
        this.distributorList = []
      },
      // 选择所属机构
      selectTreeChange(value) {
        this.clearSelectTree()
        this.getOwnersList(value.orgId)
      },
      async fetchData({ currentPage, pageSize }) {
        const query = {
          ...this._getQuery(this.query),
          currentPage,
          pageSize
        }
        if (this.date && this.date.length > 0) {
          query[this.dateType + 'StartDt'] = moment(this.date[0]).format('YYYY-MM-DD HH:mm:ss')
          query[this.dateType + 'EndDt'] = moment(this.date[1]).format('YYYY-MM-DD HH:mm:ss')
        }
        query[this.personnelType] = this.distributor || 0
        query[this.orgType] = this.orgSNNo
        this.searchParams = query
        const res = await selfBottleList(query)
        this.tableData.data = res.data.rows
        if (currentPage === 1) this.tableData.total = res.data.total
        this.flexColumnWidth()
      },
      async add() {
        await this.$refs.add.open()
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      async batchAdd() {

      },
      async openDetail(row) {
        await this.$refs.detail.open(row)
      },
      del(row, index) {
        this.$confirm('您确认删除此自有瓶吗？', '提示', {
          type: 'warning'
        }).then(() => {
          const loading = this.$message({
            message: '正在删除',
            duration: 0,
            iconClass: 'el-icon-loading'
          })
          selfBottleDel({ bottleCode: row.bottleCode }).then(() => {
            this.$notify({
              title: '提示',
              message: '操作成功',
              type: 'success',
              duration: 2000
            })
          }).finally(() => {
            loading.close()
            this.search()
          })
        })
      },
      search() {
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      // 自适应表格列宽
      flexColumnWidth() {
        this.$nextTick(() => {
          let max = 0
          const actionColDom = document.getElementsByClassName('action-col')
          for (let i = 0; i < actionColDom.length; i++) {
            if (actionColDom[i].tagName === 'TD') {
              let width = 20
              const linkDom = actionColDom[i].childNodes[0].childNodes[0].childNodes
              linkDom.forEach(it => {
                width += (it.offsetWidth + 10)
              })
              if (width > max) max = width
            }
          }
          this.actionColWidth = max > 60 ? max - 10 : 50
        })
      },
      // 导出
      async exportData() {
        const _this = this
        this.$confirm(`确定导出数据？`, '提示', {
          type: 'warning'
        }).then(() => {
          const copyColumn = JSON.parse(JSON.stringify(this.column))
          const str = {}
          copyColumn.pop()
          copyColumn.forEach((item) => {
            str[item.prop] = item.label
          })
          const params = this.searchParams
          const paramInfo = _this._getQuery(params)
          selfBottleExport({
            paramInfo: paramInfo,
            kv: str // 表格列
          }).then((res) => {
            window.open(`${this.exportDomain}/page/export/frame?key=${res.data}`, '_blank')
          })
        })
      },
      reset() {
        this.query = {
          bottleCode: '',
          operateType: ''
        }
        this.orgSNNo = ''
        this.tableData = []
        this.$refs.form.resetFields()
      }
    }
  }
</script>

<style lang="scss" scoped>
.el-form-item .el-form-item {
  margin-bottom: 0;
}
.merge-item {
  /deep/ .el-form-item__content {
    display: flex;
  }
}
.btn-group {
  display: flex;
  justify-content: space-between;
}
</style>
